<?php
/**
 * Minhlog Sphinx搜索类
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   Minh
 * @package    Minh_Search
 * @copyright  Copyright (c) 2009-2010 Minh.Shu Minh.Shu@gmail.com
 * @license    New BSD License
 * @author     Minh.Shu
 * @version    $Id: Sphinx.php 28 2010-03-11 15:28:53Z minh.shu $
 */

require_once 'SphinxApi.php';

class Minh_Search_Sphinx
{
    const MATCH_MODE = SPH_MATCH_EXTENDED;
    const HOST = 'localhost';
    const PORT = 3312;

    private static $_instance;
    private $_sphinx;

    private function  __construct()
    {
        $this->_sphinx = new SphinxClient();
    }

    public static function getInstance()
    {
        if(null === self::$_instance)
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 搜索API
     * @param string $keyword
     * @return
     */
    public function search($keyword)
    {
        $this->_sphinx->SetServer(self::HOST, self::PORT);
        $this->_sphinx->SetMatchMode(self::MATCH_MODE);
        $hits = $this->_sphinx->Query($keyword);

        if ( $hits === false )
        {
            return null;
        }
        else
        {
            if ( $this->_sphinx->GetLastWarning() )
            {
                return null;
            }

            if ( ! empty($hits["matches"]) )
            {
                $articleList = array();
                foreach ( $hits["matches"] as $doc => $docinfo )
                {
                    array_push($articleList, $docinfo['attrs']['article_id']);
                }
                $articleListString = implode(',', $articleList);
                return $articleListString;
            }
        }
        
    }
}